package cc.vv.btpartyjob.homepage.fragment

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.Bundle
import android.view.View
import cc.vv.baselibrary.bean.base.BaseResponseObj
import cc.vv.baselibrary.global.UserInfoSharePreKey
import cc.vv.baselibrary.http.BaseHttpCallBack
import cc.vv.baselibrary.util.LKPrefUtil
import cc.vv.baselibrary.util.LKToastUtil
import cc.vv.baselibrary.util.UserInfoManageUtil
import cc.vv.btpartyjob.homepage.R
import cc.vv.btpartyjob.homepage.activity.*
import cc.vv.btpartyjob.homepage.delegate.MyHomePageMainFragmentDelegate
import cc.vv.btpartyjob.homepage.moudel.bean.RankingObj
import cc.vv.btpartyjob.homepage.moudel.req.MineVolunteerProjectRequestObj
import cc.vv.btpartyjob.homepage.moudel.resp.PartyChengNuoResponseObj
import cc.vv.btpartyjob.homepage.server.HomeHttpServer
import cc.vv.btpartyjob.jnimodule.enums.RoleType
import cc.vv.btpartyjob.jnimodule.globle.BroadCastJniKey
import cc.vv.lkbasecomponent.http.LKHttp
import cc.vv.lkbasecomponent.http.lib.CallBack
import cc.vv.mvp.binder.BaseDataBinder
import cc.vv.mvp.fragment.BaseFragmentMVP
import com.dawning.utiming.task.api.HomeworkAPI
import java.util.*

/**
 * 我的主页Fragment界面
 * Created by Chen.qi on 2018/10/24.
 */
class MyHomePageMainFragment : BaseFragmentMVP<MyHomePageMainFragmentDelegate>() {


    override fun initView(bundle: Bundle?) {
        super.initView(bundle)
        setData()
        HomeHttpServer.getPartyChengNuoData(false)
        initBroadcast()
        requestDataMonth()
        requestDataTotal()
    }

    override fun initData() {

    }

    override fun onResume() {
        super.onResume()
        val string = LKPrefUtil.getString("locationKey", "")
        viewDelegate?.setLocationStr(string)
    }

    override fun bindEvenListener() {

        viewDelegate?.setOnClickListener(View.OnClickListener {
            //头像进入个人中心
            val intent = Intent(activity, MyInfoActivity::class.java)
            startActivity(intent)
        }, R.id.liv_fml_user_avatar)

        viewDelegate?.setOnClickListener(View.OnClickListener {
            //代办公文
            val intent = Intent(activity, AgencyDocumentsActivity::class.java)
            startActivity(intent)
        }, R.id.ll_fml_work)

        viewDelegate?.setOnClickListener(View.OnClickListener {
            //通知公告
            val intent = Intent(activity, NoticeActivity::class.java)
            startActivity(intent)
        }, R.id.ll_fml_notify)

        viewDelegate?.setOnClickListener(View.OnClickListener {
            //预警通知
            val intent = Intent(activity, WarningNoticeReportActivity::class.java)
            startActivity(intent)
        }, R.id.ll_fml_warning)
        viewDelegate?.setOnClickListener(View.OnClickListener {
            //我的志愿项目
            val intent = Intent(activity, MineVolunteerProjectActivity::class.java)
            startActivity(intent)
        }, R.id.ll_fml_volunteer)

        viewDelegate?.setOnClickListener(View.OnClickListener {
            //学习排行
            val intent = Intent(activity, LearnRankActivity::class.java)
            startActivity(intent)
        }, R.id.rl_fml_studyAll)
        viewDelegate?.setOnClickListener(View.OnClickListener {
            //跳转另一个apk
            try {
                // 这个是在Frageen中在Activity中就不需要加getActivity了
                val packageManager = activity.packageManager
                // 这里的packname就是从上面得到的目标apk的包名
                val intent = packageManager.getLaunchIntentForPackage("com.leapp.yapartywork")
                if (null == intent) {
                    LKToastUtil.showToastShort("您还未安装延安党建，请到市场下载")
                } else {
                    startActivity(intent)
                }
            } catch (e: Exception) {
            }
        }, R.id.iv_fml_entrance)

    }

    override fun getDelegateClass(): Class<MyHomePageMainFragmentDelegate> {
        return MyHomePageMainFragmentDelegate::class.java
    }

    override fun getDataBinder(): BaseDataBinder<*, *>? {
        return null
    }

    private fun setData() {
        val geRenInfo = UserInfoManageUtil.getGeRenInfo()
        viewDelegate?.setHeadImg(geRenInfo?.headPath)
        viewDelegate?.setUserName(geRenInfo?.name)
        viewDelegate?.setRankLevel("优秀")
        viewDelegate?.setSingelSignature(geRenInfo?.motto)
        viewDelegate?.setStudyTimeDuration(geRenInfo?.totalLearnTime)
        if (null == geRenInfo?.todayLearn) {
            viewDelegate?.setTodayStudyTime("0")
        } else {
            viewDelegate?.setTodayStudyTime(geRenInfo?.todayLearn)
        }
        viewDelegate?.setStudyRank(geRenInfo?.rank)
        viewDelegate?.setHakenkreuzNum("0")


        val userRole = UserInfoManageUtil.getUserInfo()?.userRole
        if (null != userRole && userRole.size > 0) {
            for (i in 0 until userRole.size) {
                if (RoleType.PARTY_MEMBER.type == userRole[i].type) {
                    viewDelegate?.showWarningProject(false)
                    break
                }
            }
        }


    }

    override fun getData(obj: BaseResponseObj<*>?) {
        super.getData(obj)
        when (obj) {
            is PartyChengNuoResponseObj -> {
                val data = obj.data
                if (null != data) {
                    LKPrefUtil.putString(UserInfoSharePreKey.GE_REN_CHENG_NUO_DATA, data.content)
                    viewDelegate?.setIPromise(data.content)
                }
            }
        }
    }


    /**
     * 刷新数据的广播
     */
    private var mMyBroadCast: MyBroadCast? = null

    /**
     * 刷选器
     */
    private var filter: IntentFilter? = null

    /**
     * 初始化广播（接收头像和用户名改变的广播）
     */
    private fun initBroadcast() {
        if (null == mMyBroadCast) {
            mMyBroadCast = MyBroadCast()
            filter = IntentFilter()
            filter?.addAction(BroadCastJniKey.BROAD_CAST_KEY_CHENG_NUO_UPDATA)
            context.registerReceiver(mMyBroadCast, filter)
        }
    }

    /**
     * 广播接收
     */
    private inner class MyBroadCast : BroadcastReceiver() {
        override fun onReceive(context: Context, intent: Intent?) {
            //接收头像修改广播，发送对应的消息
            if (intent?.action == BroadCastJniKey.BROAD_CAST_KEY_CHENG_NUO_UPDATA) {
                val request = MineVolunteerProjectRequestObj()
                LKHttp.get(HomeworkAPI.getHotChengNuoDataUrl, request, PartyChengNuoResponseObj::class.java,
                        object : BaseHttpCallBack<PartyChengNuoResponseObj>() {
                            override fun onSuccess(url: String?, obj: PartyChengNuoResponseObj?) {
                                super.onSuccess(url, obj)
                                val data = obj?.data
                                viewDelegate?.setIPromise(data?.content)
                            }

                        }, false)
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        if (null != mMyBroadCast) {
            context.unregisterReceiver(mMyBroadCast)
        }
    }


    /**
     * 总排名
     */
    private fun requestDataTotal() {
        val params = HashMap<String, Any>()
        params.put("SESSIONID", UserInfoManageUtil.getUserInfo()?.sessionid + "")
        LKHttp.post(HomeworkAPI.studyRankTotalList, params, RankingObj::class.java, object : CallBack<RankingObj>() {
            override fun onSuccess(url: String, obj: RankingObj?) {
                super.onSuccess(url, obj)
                if (obj != null) {
                    val rankList = obj.rankList
                    if (rankList != null && rankList.size > 0) {
                        LKPrefUtil.putObject(UserInfoSharePreKey.TOTAL_PAIMING_TOP, rankList)
                    }
                    val branchRankList = obj.branchRankList
                    if (branchRankList != null && branchRankList.size > 0) {
                        LKPrefUtil.putObject(UserInfoSharePreKey.TOTAL_PAIMING_BOTTOM, branchRankList)
                    }
                }
            }

            override fun onFinish(url: String, resultCode: Int, isLoading: Boolean) {
                super.onFinish(url, resultCode, isLoading)
                loading.closeLoading()
            }

            override fun onSuccess(url: String, resultText: String, obj: RankingObj) {
                super.onSuccess(url, resultText, obj)
            }
        }, false)
    }

    /**
     * 月排名
     */
    private fun requestDataMonth() {
        val params = HashMap<String, Any>()
        params.put("SESSIONID", UserInfoManageUtil.getUserInfo()?.sessionid + "")
        LKHttp.post(HomeworkAPI.studyRankMonthList, params, RankingObj::class.java, object : CallBack<RankingObj>() {
            override fun onSuccess(url: String, obj: RankingObj?) {
                super.onSuccess(url, obj)
                if (obj != null) {

                    val rankList = obj.rankList
                    if (rankList != null && rankList.size > 0) {
                        LKPrefUtil.putObject(UserInfoSharePreKey.YUE_PAIMING_TOP, rankList)
                    }
                    val branchRankList = obj.branchRankList
                    if (branchRankList != null && branchRankList.size > 0) {
                        LKPrefUtil.putObject(UserInfoSharePreKey.YUE_PAIMING_BOTTOM, branchRankList)
                    }
                }
            }

            override fun onFinish(url: String, resultCode: Int, isLoading: Boolean) {
                super.onFinish(url, resultCode, isLoading)
                loading.closeLoading()
            }

            override fun onSuccess(url: String, resultText: String, obj: RankingObj) {
                super.onSuccess(url, resultText, obj)
            }
        }, false)
    }


}